"""
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    created by lei.chang on '25/09/2023'
    comment: 桌面启动
"""
import sys
import traceback
from PyQt5.QtWidgets import QApplication, QStyle, qApp, QDesktopWidget
from PyQt5.QtCore import QSize, Qt

from project.view.main_window import MainWindow
from project.lib.common import logger


def global_exception_hook(exctype, value, tb):
    """全局异常捕获钩子"""
    # 格式化错误信息
    error_msg = ''.join(traceback.format_exception(exctype, value, tb))

    logger.critical(error_msg)


if __name__ == "__main__":
    """
    """
    # 设置全局异常钩子
    sys.excepthook = global_exception_hook

    if hasattr(Qt, "AA_EnableHighDpiScaling"):
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    if hasattr(Qt, "AA_UseHighDpiPixmaps"):
        QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps, True)

    app = QApplication(sys.argv)

    # 1. 可用桌面几何
    ag = QDesktopWidget().availableGeometry()
    sw, sh = ag.width(), ag.height()

    # 2. 先拿一条「系统装饰」高度
    style = qApp.style()
    frame = style.pixelMetric(QStyle.PM_TitleBarHeight)  # 标题栏
    border = style.pixelMetric(QStyle.PM_MdiSubWindowFrameWidth)  # 左右边框
    decoration_h = frame + border * 2  # 保守留 30~40 px

    # 3. 目标比例 (高 / 宽)
    target_ratio = 9 / 16

    # 4. 在「可用高度」里先减掉装饰带，再算客户区
    avail_h = sh - decoration_h

    if avail_h / sw > target_ratio:  # 太高 → 上下留空
        h_client = int(sw * target_ratio)
        w_client = sw
    else:  # 太宽 → 左右留空
        w_client = int(avail_h / target_ratio)
        h_client = avail_h

    # 5. 窗口总尺寸 = 客户区 + 装饰带
    total_w = w_client
    total_h = h_client + decoration_h

    # 6. 居中
    x = ag.left() + (sw - total_w) // 2 if sw > total_w else 0
    y = ag.top() + (sh - total_h) // 2 if sh > total_h else 0

    window = MainWindow()
    window.setGeometry(x, y, total_w, total_h)
    window.setMinimumSize(QSize(int(total_w*0.6), int(total_h*0.6)))
    window.show()

    sys.exit(app.exec_())
